#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 4e4 + 10, M = N * 2;
int h[N], ne[M], e[M], idx;
int q[N];
int depth[N], fa[N][16];
int n, m;
void add(int a, int b)
{
	e[idx] = b;
	ne[idx] = h[a];
	h[a] = idx++;
}
void bfs(int root)
{
	memset(depth, 0x3f, sizeof(depth));
	q[0] = root;
	depth[root] = 1;
	depth[0] = 0;
	int hh = 0, tt = 0;
	while (hh <= tt) {
		int t = q[hh++];
		for (int i = h[t]; ~i; i = ne[i]) {
			int j = e[i];
			if (depth[j] > depth[t] + 1) {
				depth[j] = depth[t] + 1;
				q[++tt] = j;
				fa[j][0] = t;
				for (int k = 1; k <= 15; k++) {
					fa[j][k] = fa[fa[j][k - 1]][k - 1];
				}
			}
		}
	}
}
int LCA(int a, int b)
{
	if (depth[a] < depth[b]) {
		swap(a, b);
	}
	for (int k = 15; k >= 0; k--) {
		if (depth[fa[a][k]] >= depth[b]) {
			a = fa[a][k];
		}
	}
	if (a == b) {
		return a;
	}
	for (int k = 15; k >= 0; k--) {
		if (fa[a][k] != fa[b][k]) {
			a = fa[a][k];
			b = fa[b][k];
		}
	}
	return fa[a][0];
}
int main()
{
	cin >> n;
	int a, b;
	int root = 0;
	memset(h, -1, sizeof(h));
	for (int i = 0; i < n; i++) {
		cin >> a >> b;
		if (b == -1) {
			root = a;
		}
		else {
			add(a, b);
			add(b, a);
		}
	}
	bfs(root);
	cin >> m;
	while (m--) {
		cin >> a >> b;
		int p = LCA(a, b);
		if (p == a) {
			cout << 1 << endl;
		}
		else if (p == b) {
			cout << 2 << endl;
		}
		else {
			cout << 0 << endl;
		}
	}
	return 0;
}